/**
 * Datart
 *
 * Copyright 2021
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { Form, FormInstance, Input } from "antd";
import { ModalForm, ModalFormProps } from "app/components";
import { useCallback, useContext, useEffect, useRef } from "react";
import { SaveModelFormContext, useSaveModelFormContext } from "./SaveModelFormContext";
import { useAppSelector } from "app/hooks";

type SaveFormProps = Omit<ModalFormProps, "type" | "visible" | "onSave">;

export function SaveModelForm({ formProps, ...modalProps }: SaveFormProps) {
  const { type, visible, initialValues, onSave, onCancel, onAfterClose } = useContext(SaveModelFormContext);
  // const { type, visible, initialValues, onSave, onCancel, onAfterClose } = useSaveModelFormContext();
  const saveLoading = useAppSelector((state) => state.counter.modelInfoLoading);

  // const currentEditingView = useSelector(selectCurrentEditingView);
  const formRef = useRef<FormInstance>();

  useEffect(() => {
    if (initialValues) {
      formRef.current?.setFieldsValue({
        ...initialValues,
      });
    }
  }, [initialValues]);

  const save = useCallback(
    (values) => {
      onSave(
        {
          ...values,
          config: {},
        },
        onCancel
      );
    },
    [onSave, onCancel]
  );

  const afterClose = useCallback(() => {
    formRef.current?.resetFields();
    onAfterClose && onAfterClose();
  }, [onAfterClose]);

  return (
    <ModalForm
      formProps={formProps}
      {...modalProps}
      title={"基本信息"}
      type={type}
      open={visible}
      confirmLoading={saveLoading}
      onSave={save}
      onCancel={onCancel}
      afterClose={afterClose}
      ref={formRef}
    >
      <Form.Item
        name="modelName"
        label={"模型名称"}
        getValueFromEvent={(event) => event.target.value?.trim()}
        rules={[
          {
            required: true,
            message: `模型名称不能为空`,
          },
        ]}
      >
        <Input />
      </Form.Item>
      <Form.Item name="modelTradeType" label={"模型所属行业"}>
        <Input />
      </Form.Item>
      <Form.Item name="modelCategory" label={"模型所属目录"}>
        <Input />
      </Form.Item>

      <Form.Item name="auditMattersClub" label={"审计事项"}>
        <Input />
      </Form.Item>
      <Form.Item name="modelClassfication" label={"模型分类"}>
        <Input />
      </Form.Item>
      <Form.Item name="modelRating" label={"推荐指数"}>
        <Input />
      </Form.Item>
    </ModalForm>
  );
}
